package com.example.gcode;

import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.android.AuthActivity;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;
import com.gcloud.dropbox.ListDropBoxFile;
import com.gcloud.dto.GCloudFile;
import com.gcloud.googledrive.UploadGoogleFile;
import com.gfilechooser.utils.FileUtils;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.FileList;
import com.utils.GCloudUtil;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class GoogleDriveSyncronized extends Activity {
	private static String TAG = GoogleDriveSyncronized.class.getSimpleName();
	private ProgressDialog pDialog;
	private static final String TAG_NOMBRE = "TAG_NOMBRE";
	private static final String TAG_FILE_ID = "TAG_FILE_ID";
	Drive service;
	GoogleAccountCredential credential;
	private static final int REQUEST_ACCOUNT = 1;
	private static final int REQUEST_CODE = 100;

	/* DROP BOX THINGS */
	final static private String APP_KEY = "bx9eufdsdzpbxs5";
	final static private String APP_SECRET = "tz6vorkhj2xvfv1";
	private static boolean mLoggedIn;
	final static private String ACCOUNT_PREFS_NAME = "prefs";
	final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
	final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
	DropboxAPI<AndroidAuthSession> mApi;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.archivos_list);
		credential = GoogleAccountCredential.usingOAuth2(this,
				DriveScopes.DRIVE);
		credential.setSelectedAccountName("guilletec@gmail.com");
		service = getDriveServices(credential);
		new CargarArchivos().execute();
//		startActivityForResult(credential.newChooseAccountIntent(),
//				REQUEST_ACCOUNT);
	}

	private void showChooser() {
		Intent target = FileUtils.createGetContentIntent();
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));
		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			Log.i("showChooser", e.getLocalizedMessage());
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i("jalskjdf", "guaro!!");
		switch (item.getItemId()) {
		case R.id.menu_upload:

			Log.i("here", "upload");
			showChooser();
			break;
		case R.id.menu_download:
			Log.i("here", "download");
			break;
		case R.id.menu_delete:
			Log.i("here", "delete");
			break;
		case R.id.menu_bookmark:
			Log.i("here", "bookmark");
			break;
		case R.id.menu_save:
			Log.i("here", "save");
			break;
		case R.id.menu_search:
			Log.i("here", "search");
			break;
		case R.id.menu_google_drive:
			Log.i("here", "google drive");
			break;
		case R.id.menu_dropbox:
			Log.i("here", "dropbox");
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_layout, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT:
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {
				String accountName = data
						.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				Log.i("on activity result: ",accountName);
				credential.setSelectedAccountName("guilletec@gmail.com");
				service = getDriveServices(credential);
				new CargarArchivos().execute();
			}
			break;
		case REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					final Uri uri = data.getData();
					try {
						final File file = FileUtils.getFile(uri);
						showToast("File selected: " + file.getAbsolutePath());
						UploadGoogleFile googleFile = new UploadGoogleFile(
								service, GoogleDriveSyncronized.this, file);
						googleFile.execute();
					} catch (Exception e) {
						Log.e("FileSelectorTestActivity", "File select error",
								e);
					}
				}
			}
			break;
		}
	}

	private Drive getDriveServices(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
				new GsonFactory(), credential).build();
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	class CargarArchivos extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(GoogleDriveSyncronized.this);
			pDialog.setMessage("cargando archivos ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		GCloudSingleton gCloudSingleton;

		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... voids) {

			Log.i("GCLOUD", "Ya entre a doInBackground :)");

			// new ListGoogleFile(service, getApplicationContext()).execute();

			// return "true";
			List<com.google.api.services.drive.model.File> result = new ArrayList<com.google.api.services.drive.model.File>();
			Files.List request = null;
			try {
				request = service.files().list();
				Log.i("retrieveAllFiles()", "getting files");
			} catch (IOException e1) {
				Log.i("retrieveAllFiles()", "something goes really wrong");
			}
			Log.i("retrieveAllFiles()", "to execute get Files");
			if (request == null) {
				Log.i("retrieveAllFiles() inside run",
						"to execute get Files inside run");
				return "false";
			}
			Log.i("retrieveAllFiles()", "request well formed ");
			do {
				try {
					Log.i("ListGoogleFile", "Getting files");
					FileList files = request.execute();
					result.addAll(files.getItems());
					request.setPageToken(files.getNextPageToken());
					Log.i("ListGoogleFile", "Getting files at the end");
				} catch (SocketException s) {
					Log.i("ListGoogleFile", " SocketException: " + s);
					return "false";
				} catch (IOException e) {
					System.out.println("An error occurred: " + e);
					request.setPageToken(null);
					return "false";
				}
			} while (request.getPageToken() != null
					&& request.getPageToken().length() > 0);
			// TODO call singleton here

			if (result != null) {
				gCloudSingleton = GCloudSingleton.getInstance();
				gCloudSingleton.setFilesFromAllService(GCloudUtil
						.googleFilesToGCloudFiles(result));
			}
			// String datasFromFilesD = "";
			for (com.google.api.services.drive.model.File file : result) {
				// datasFromFilesD += file.getTitle() + "  ";
				Log.i("RetrieveAllFiles", "File title: " + file.getTitle());
			}
			// showToast(datasFromFilesD);
			return "true";
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			if (file_url.equalsIgnoreCase("true")) {
				showToast("everything well done");
				Intent newIntent = new Intent(GoogleDriveSyncronized.this,
						Archivos.class);
				startActivity(newIntent);
			} else {
				showToast("probably something goes wrong");
			}

			// if(){
			// startActivityForResult(credential.newChooseAccountIntent(),
			// REQUEST_ACCOUNT);
			// }
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */

					// GCloudSingleton gSingleton =
					// GCloudSingleton.getInstance();
					// Log.i("Archivos:", " "
					// + gSingleton.getFilesFromAllService().size());
					// ListAdapter adapter = new SimpleAdapter(Archivos.this,
					// gSingleton.getFilesFromAllService(),
					// R.layout.archivos_list_item, new String[] {
					// TAG_NOMBRE, TAG_FILE_ID }, new int[] {
					// R.id.list_nombre, R.id.list_service });
					// updating listview
					// setListAdapter(adapter);
				}
			});

		}

	}
}
